<?php
/**
 * Created by PhpStorm.
 * User: 84071
 * Date: 2018-04-25
 * Time: 9:49
 */
namespace app\api\controller;

use app\common\controller\Apibase;
use app\common\model\OrderPlay;
use app\common\model\OrderShop;
use app\common\model\UserMoney;
use weixinhack\WxBase;

class Pay extends Apibase {

    //  查询支付宝交易状态
    public function alipayend(){
        $getdata = request()->param();
        $getdata = datatrim($getdata);
        $data['out_trade_no'] = $getdata['out_trade_no'];
        $alipayend = controller('Alipay')->get_playend($data);
        if(!empty($alipayend)){
            $order['pricemoney'] = $alipayend->alipay_trade_query_response->total_amount * 100;
            $order['status'] = $alipayend->alipay_trade_query_response->trade_no;
            $order['lsoid'] = $alipayend->alipay_trade_query_response->out_trade_no;
            if($this->order_end($order)){
                if(!empty($getdata['sign'])){
                    $this->success("支付成功",'Index/index');
                }
                return "SUCCESS";
            }
        }
    }
    //  查询微信交易状态
    public function wxpayend(){
        $getdata = request()->param();
        $getdata = datatrim($getdata);
        $wxmodel = new WxBase();
        $endplay = $wxmodel->get_payend($this->webdb,$getdata['out_trade_no']);
        if($endplay['return_code'] == 'SUCCESS' && $endplay['result_code'] == 'SUCCESS' && $endplay['trade_state'] == 'SUCCESS'){
            $order['pricemoney'] = $endplay['total_fee'];
            $order['status'] = $endplay['transaction_id'];
            $order['lsoid'] = $endplay['out_trade_no'];
            if($this->order_end($order)){
                return "SUCCESS";
            }
        }
    }

    /**
     * @param $data 包含订单返回的实际支付金额，临时订单号，结算商订单号
     * 修改临时订单号，并删除多余未付款临时订单号
     * 修改订单支付状态
     * 减少产品库存
     * 处理三级分销
     * @return bool 返回继续执行
     */
    public function order_end($data){
        $playmodel = new OrderPlay();
        $gomodel = new OrderShop();
        $ormodel = new \app\common\model\Order();
        $moneymodel = new UserMoney();
        //  修改支付单号并删除多余订单
        $orderplay = $playmodel->where('lsoid',$data['lsoid'])->find()->toArray();
        $orderplay['status'] = $data['status'];
        $playmodel->allowField(true)->isUpdate(true)->save($orderplay,['lsoid'=>$orderplay['lsoid']]);
        $playmodel->where('oid',$orderplay['oid'])->where('status','0')->delete();
        //  修改支付状态
        $order = $ormodel->where('oid',$orderplay['oid'])->find()->toArray();
        $order['playtime'] = time();
        $order['pricemoney'] = $data['pricemoney'];
        $order['playstatus'] = '1';
        $ormodel->allowField(true)->isUpdate(true)->save($order,['oid'=>$order['oid']]);
        if($order['mid'] == '1001' || $order['mid'] == '1002'){
            return true;
        }
        if($order['mid'] == '1003'){
            $addmoney = floor( $order['pricemoney'] / 100);
            $newaddmoney = array(
                'uid' => $order['uid'],
                'money_class' => '0',
                'addcont' => '8',
                'fuid' => '0',
                'cont' => "用户充值{$addmoney}元",
            );
            $newaddmoney = $moneymodel->adduser($newaddmoney,$addmoney);
            $moneymodel->setAttr('id',null)->isUpdate(false)->save($newaddmoney);
            unset($addmoney);
            unset($newaddmoney);
            return true;
        }
        //  保证金
        if($order['mid'] == '1004'){
            $newuserdata = array(
                'uid' => $order['uid'],
                'user_money' => floor( $order['pricemoney'] / 100),
            );
            model('User')->edit_user($newuserdata);
            return true;
        }
        //  清空购物车
        $orderShop = $gomodel->where('uid',$order['uid'])->where('mid',$order['mid'])->find()->toArray();
        $orderShop['aids'] = '';
        $gomodel->allowField(true)->isUpdate(true)->save($orderShop,['id'=>$orderShop['id']]);
        //  处理产品数量
        $shop = unserialize($order['conf']);
        foreach ($shop['shop'] as $k => $v){
            $donshop = null;
            $donshop = db('article_content_'.$order['mid'])->where('aid',$v['aid'])->find();
            if(!empty($donshop['stock'])) {
                $donshop['stock'] = $donshop['stock'] - $v['num'];
                db('article_content_' . $order['mid'])->where('aid', $donshop['aid'])->setField('stock', $donshop['stock']);
            }
        }
        //  处理推广
        $puidnum = model('UserSpread')->where('uid',$order['uid'])->count();
        if($puidnum > 0){
            $puser = model('UserSpread')->where('uid',$order['uid'])->find()->toArray();
            $monty = array(
                'uid' => $puser['puid'],
                'addcont' => '3',
            );

            if(!empty($puser['puid'])){
                $usergroup_id = model('UserData')->where('uid',$puser['puid'])->value('group_id');
                if($usergroup_id == '6'){
                    $money_class = $this->webdb['spread_money_lsclass'];
                    $addmoney = $order['pricemoney'] * $this->webdb['user_shop_lsgold'];
                }else{
                    $money_class = $this->webdb['spread_money_class'];
                    $addmoney = $order['pricemoney'] * $this->webdb['user_shop_gold'];
                }
                if($money_class == '0'){
                    $money_name = '元';
                }elseif($money_class == '1'){
                    $money_name = $this->webdb['moneyname'];
                }
                $monty['money_class'] = $money_class;
                $addmoney = floor($addmoney / 10000);
                $usermoney = $moneymodel->adduser($monty,$addmoney);
                $usermoney['cont'] = '下级用户下单：'.$order['title'].'，增加：'.$addmoney.$money_name;
                $usermoney['fuid'] = $order['uid'];
                $usermoney['uid'] = $monty['uid'];
                $usermoney['addtime'] = time();
                $moneymodel->setAttr('id',null)->isUpdate(false)->save($usermoney);
                unset($addmoney);
                unset($usermoney);
            }
            if(!empty($puser['euid'])){
                $monty['addcont'] = '4';
                $ergroup_id = model('UserData')->where('uid',$puser['euid'])->value('group_id');
                if($ergroup_id == '6'){
                    $money_class = $this->webdb['spread_money_lsclass'];
                    $addmoney = $order['pricemoney'] * $this->webdb['user_shop_lsergold'];
                }else{
                    $money_class = $this->webdb['spread_money_class'];
                    $addmoney = $order['pricemoney'] * $this->webdb['user_shop_ergold'];
                }
                if($money_class == '0'){
                    $money_name = '元';
                }elseif($money_class == '1'){
                    $money_name = $this->webdb['moneyname'];
                }
                $monty['money_class'] = $money_class;
                $addmoney = floor($addmoney / 10000);
                $usermoney = model('UserMoney')->adduser($monty,$addmoney);
                $usermoney['cont'] = '间级用户下单：'.$order['title'].'，增加：'.$addmoney.$money_name;
                $usermoney['fuid'] = $order['uid'];
                $usermoney['uid'] = $puser['euid'];
                $usermoney['addtime'] = time();
                $moneymodel->setAttr('id',null)->isUpdate(false)->save($usermoney);
                unset($addmoney);
                unset($usermoney);
            }
        }
        return true;
    }
    //  生成临时订单号并存入数据库
    public function linshioid($oid){
        $numbers = range (1,50);
        shuffle ($numbers);
        $num=8;
        $result = array_slice($numbers,0,$num);
        $result = implode('',$result);
        $newname = 'LSPAY'.date("Ymd");
        for ( $i = 0; $i < 8; $i++ ) {
            $newname .= substr($result, mt_rand(0, strlen($result) - 1), 1);
        }
        $data['oid'] = $oid;
        $data['lsoid'] = $newname;
        model('OrderPlay')->save($data);
        return $newname;
    }
}